<?php

namespace app\index\service;

use app\common\model\Trade;
use app\common\service\GatewayClientServer;
use app\index\dao\TradeDao;
use app\index\model\UM as UM;
use ShidianUtil\Exception\DataNotExistException;
use think\exception\ValidateException;

/**
 * Class OrderRefundService
 * @package app\index\service
 */
class OrderRefundService
{
    // dao
    private TradeDao $tradeDao;

    public function __construct(TradeDao $tradeDao)
    {
        $this->tradeDao = $tradeDao;
    }

    /**
     * 更新
     * @param UM $user
     * @param int $id
     * @param array $params
     * @return Trade
     */
    public function modify(UM $user, int $id, array $params): Trade
    {
        if (is_blank($params['refundReason'] ?? null)) {
            throw new ValidateException('请输入退款原因');
        }

        //这里如果要修改查询，建议把查询就放到这里
        $record = Trade::field(true)->where('id', $id)->find();

        if (is_null($record)) {
            throw new DataNotExistException('该订单不存在或已被删除');
        }

        if ($user->id != $record->memberId) {
            throw new ValidateException('您不能为该订单申请退款');
        }

        if ($record->tradeType == TRADE_BALANCE_RECHARGE || $record->tradeType == TRADE_TOKEN_RECHARGE) {
            throw new ValidateException('充值订单不能退款');
        }
        if ($record->tradeType == TRADE_CASH) {
            throw new ValidateException('提现订单不能退款');
        }
        if ($record->tradeType == TRADE_AXB) {
            throw new ValidateException('通信币订单不能退款');
        }
        if ($record->tradeType == TRADE_SOURCE) {
            throw new ValidateException('获客卡订单不能退款');
        }

        // 支付状态
        if ($record->payStatus != Trade::PAID) {
            throw new ValidateException('该订单未支付');
        }

        // 退款状态
        if ($record->refundStatus == Trade::REFUNDING) {
            throw new ValidateException('该订单正在退款审核中，请勿重复提交');
        }
        if ($record->refundStatus == Trade::REFUNDED) {
            throw new ValidateException('该订单已退款成功');
        }

        // 结算状态
        if ($record->settleStatus == Trade::SETTLING || $record->settleStatus == Trade::SETTLED) {
            throw new ValidateException('该订单已结算，不能退款');
        }

        // 申请退款
        $record->refundStatus = Trade::REFUNDING;
        $record->refundCheckStatus = Trade::UNCHECKED;
        $record->refundReason = $params['refundReason'];
        $record->refundRequestTime = time();
        $record->save();

        // 订单申请退款后，更新红点
        $data = [
            'action' => REDDOT,
            'data' => [],
        ];
        $this->getGatewayClientServer()->sendToUid($record->memberId, json_encode($data));

        return $record;
    }

    private function getGatewayClientServer(): GatewayClientServer
    {
        return app(GatewayClientServer::class);
    }
}
